package com.tencent.liteav.demo.player.demo;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.tencent.liteav.demo.player.R;
import com.tencent.liteav.demo.superplayer.SuperPlayerDef;
import com.tencent.liteav.demo.superplayer.SuperPlayerGlobalConfig;
import com.tencent.liteav.demo.superplayer.SuperPlayerModel;
import com.tencent.liteav.demo.superplayer.SuperPlayerVideoId;
import com.tencent.liteav.demo.superplayer.SuperPlayerView;
import com.tencent.liteav.demo.superplayer.helper.IntentUtils;
import com.tencent.liteav.demo.superplayer.helper.PictureInPictureHelper;
import com.tencent.liteav.demo.vodcommon.entity.VideoModel;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class SuperPlayerDetailActivity extends FragmentActivity implements SuperPlayerView.OnSuperPlayerViewCallback, ActivityCompat.OnRequestPermissionsResultCallback{
    private static final String TAG = "SuperPlayerDetailActivi";
    private SuperPlayerView mSuperPlayerView;
    private boolean                  mIsManualPause = false;
    private boolean                  mIsEnteredPIPMode = false;
    private LocalExitPIPBroadcastReceiver localExitPIPBroadcastReceiver;
    private static final String KEY_models = "models";
    private static final String KEY_model = "model";
    private List<VideoModel> superModels;
    private VideoModel videoModel;

    public static void startForList(Context context,ArrayList<VideoModel> models) {
        Intent starter = new Intent(context, SuperPlayerDetailActivity.class);
        starter.putExtra(KEY_models,models);
        context.startActivity(starter);
    }

    public static void startForModel(Context context,VideoModel model) {
        Intent starter = new Intent(context, SuperPlayerDetailActivity.class);
        starter.putExtra(KEY_model,model);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.superplayer_activity_supervod_player_detail);

        initView();
        initData();
    }

    /**
     * Display the player view in a 16:9 aspect ratio, with priority given to fully filling the width.
     *
     * 以16：9 比例显示播放器view，优先保证宽度完全填充
     */
    private void adjustSuperPlayerViewAndMaskHeight() {
        final int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams layoutParams = mSuperPlayerView.getLayoutParams();
        layoutParams.width = screenWidth;
        layoutParams.height = (int) (screenWidth * SuperPlayerGlobalConfig.PLAYER_VIEW_DISPLAY_RATIO);
        mSuperPlayerView.setLayoutParams(layoutParams);
    }

    private void initView(){
        mSuperPlayerView = (SuperPlayerView) findViewById(R.id.superVodPlayerView);
        mSuperPlayerView.setPlayerViewCallback(this);
        adjustSuperPlayerViewAndMaskHeight();
    }

    private void initData(){
        Intent intent = getIntent();
        if (intent.hasExtra(KEY_models)){
            superModels = (List<VideoModel>) intent.getSerializableExtra(KEY_models);
            mSuperPlayerView.setQualityVisible(true);
            List<SuperPlayerModel> superPlayerModelList = new ArrayList<>();
            for (VideoModel videoModel : superModels) {
                superPlayerModelList.add(videoModel.convertToSuperPlayerModel());
            }
            mSuperPlayerView.playWithModelListNeedLicence(superPlayerModelList, true, 0);
        }else if (intent.hasExtra(KEY_model)){
            videoModel = (VideoModel) intent.getSerializableExtra(KEY_model);
            mSuperPlayerView.setQualityVisible(true);
            final SuperPlayerModel superPlayerModelV3 = new SuperPlayerModel();
            superPlayerModelV3.appId = videoModel.appid;
            if (videoModel.dynamicWaterConfig != null) {
                superPlayerModelV3.dynamicWaterConfig = videoModel.dynamicWaterConfig;
            }
            if (!TextUtils.isEmpty(videoModel.videoURL)) {
                superPlayerModelV3.title = videoModel.title;
                superPlayerModelV3.url = videoModel.videoURL;
            }
            if (videoModel.multiVideoURLs != null && videoModel.multiVideoURLs.size() > 0) {
                superPlayerModelV3.multiURLs = new ArrayList<>();
                for (VideoModel.VideoPlayerURL modelURL : videoModel.multiVideoURLs) {
                    superPlayerModelV3.multiURLs.add(new SuperPlayerModel.SuperPlayerURL(modelURL.url, modelURL.title));
                }
            }

            if (!TextUtils.isEmpty(videoModel.fileid)) {
                superPlayerModelV3.videoId = new SuperPlayerVideoId();
                superPlayerModelV3.videoId.fileId = videoModel.fileid;
                superPlayerModelV3.videoId.pSign = videoModel.pSign;
            }
            superPlayerModelV3.playDefaultIndex = videoModel.playDefaultIndex;
            superPlayerModelV3.subtitleSourceModelList = videoModel.subtitleSourceModelList;
            superPlayerModelV3.title = videoModel.title;
            superPlayerModelV3.playAction = videoModel.playAction;
            superPlayerModelV3.placeholderImage = videoModel.placeholderImage;
            superPlayerModelV3.coverPictureUrl = videoModel.coverPictureUrl;
            superPlayerModelV3.duration = videoModel.duration;
            superPlayerModelV3.videoQualityList = videoModel.videoQualityList;
            superPlayerModelV3.isEnableCache = videoModel.isEnableDownload;
            mSuperPlayerView.playWithModelNeedLicence(superPlayerModelV3);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (PictureInPictureHelper.hasPipPermission(this)
                && (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N)
                && isInPictureInPictureMode()) {
            mSuperPlayerView.onResume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsEnteredPIPMode = false;
        if (mSuperPlayerView.getPlayerState() == SuperPlayerDef.PlayerState.PLAYING
                || mSuperPlayerView.getPlayerState() == SuperPlayerDef.PlayerState.PAUSE) {
            Log.i(TAG, "onResume state :" + mSuperPlayerView.getPlayerState());
            if (!mIsManualPause) {
                mSuperPlayerView.onResume();
            }
            if (mSuperPlayerView.getPlayerMode() == SuperPlayerDef.PlayerMode.FLOAT) {
                mSuperPlayerView.switchPlayMode(SuperPlayerDef.PlayerMode.WINDOW);
            }
        }
        if (mSuperPlayerView.getPlayerMode() == SuperPlayerDef.PlayerMode.FULLSCREEN) {
            View decorView = getWindow().getDecorView();
            if (decorView == null) return;
            if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
                decorView.setSystemUiVisibility(View.GONE);
            } else if (Build.VERSION.SDK_INT >= 19) {
                int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
                decorView.setSystemUiVisibility(uiOptions);
            }
        }
        mSuperPlayerView.setNeedToPause(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause state :" + mSuperPlayerView.getPlayerState());
        if (PictureInPictureHelper.hasPipPermission(this)
                && (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N)
                && isInPictureInPictureMode()) {
            mIsEnteredPIPMode = true;
            return;
        }
        if (mSuperPlayerView.getPlayerMode() != SuperPlayerDef.PlayerMode.FLOAT) {
            if (mSuperPlayerView.getPlayerState() == SuperPlayerDef.PlayerState.PAUSE) {
                mIsManualPause = true;
            } else {
                mIsManualPause = false;
            }
            mSuperPlayerView.onPause();
            mSuperPlayerView.setNeedToPause(true);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (PictureInPictureHelper.hasPipPermission(this) && mIsEnteredPIPMode) {
            PowerManager manager = (PowerManager)getSystemService(POWER_SERVICE);
            if ((android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N)
                    && !manager.isInteractive()) {
                mSuperPlayerView.onPause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSuperPlayerView.release();
        if (mSuperPlayerView.getPlayerMode() != SuperPlayerDef.PlayerMode.FLOAT) {
            mSuperPlayerView.resetPlayer();
        }
        unRegisterLocalExitPipReceiver();
    }

    @Override
    public void onStartFullScreenPlay() {

    }

    @Override
    public void onStopFullScreenPlay() {

    }

    @Override
    public void onClickFullReturnBtn() {
        mSuperPlayerView.switchPlayMode(SuperPlayerDef.PlayerMode.WINDOW);
    }

    @Override
    public void onClickFloatCloseBtn() {
        // If the close button in the floating window is clicked, the entire playback is ended.
        mSuperPlayerView.resetPlayer();
        finish();
    }

    @Override
    public void onClickSmallReturnBtn() {
        // If the back button is clicked in small window mode, start floating playback.
        mSuperPlayerView.resetPlayer();
        finish();
    }

    @Override
    public void onStartFloatWindowPlay() {
        // After starting floating playback, return directly to the desktop for floating playback.
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        IntentUtils.safeStartActivity(this, intent);
    }

    @Override
    public void onPlaying() {

    }

    @Override
    public void onPlayEnd() {

    }

    @Override
    public void onError(int code) {

    }

    @Override
    public void onShowCacheListClick() {
        Intent intent = new Intent(this, VideoDownloadListActivity.class);
        IntentUtils.safeStartActivity(this, intent);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        mSuperPlayerView.onRequestPermissionsResult(requestCode, grantResults);
    }

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        mSuperPlayerView.onPictureInPictureModeChanged(isInPictureInPictureMode);
        if (isInPictureInPictureMode) {
            registerLocalExitPipReceiver();
        } else {
            unRegisterLocalExitPipReceiver();
        }
        if (getLifecycle().getCurrentState() == Lifecycle.State.CREATED
                && (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)) {
            finishAndRemoveTask();
        }
    }

    private void registerLocalExitPipReceiver() {
        if (localExitPIPBroadcastReceiver == null) {
            localExitPIPBroadcastReceiver = new LocalExitPIPBroadcastReceiver(this);
        }
        IntentFilter intentFilter = new IntentFilter(LocalExitPIPBroadcastReceiver.EXIT_PIP);
        LocalBroadcastManager.getInstance(this).registerReceiver(localExitPIPBroadcastReceiver, intentFilter);
    }

    private void unRegisterLocalExitPipReceiver() {
        if (localExitPIPBroadcastReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(localExitPIPBroadcastReceiver);
            localExitPIPBroadcastReceiver = null;
        }
    }

    public static void exitPIP(Context context){
        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(LocalExitPIPBroadcastReceiver.EXIT_PIP));
    }

    private static class LocalExitPIPBroadcastReceiver extends BroadcastReceiver {
        public static final String EXIT_PIP = "com.tencent.liteav.demo.player.demo.SuperPlayerActivity.LocalExitPIPBroadcastReceiver.EXIT_PIP";
        private final WeakReference<SuperPlayerDetailActivity> activityRef;

        LocalExitPIPBroadcastReceiver(SuperPlayerDetailActivity activity) {
            activityRef = new WeakReference<>(activity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (EXIT_PIP.equals(intent.getAction()) && activityRef.get() != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    activityRef.get().finishAndRemoveTask();
                } else {
                    activityRef.get().finish();
                }
            }
        }
    }

}
